package org.xxx.socket.controller;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xxx.socket.attribute.EqmContext;
import org.xxx.socket.init.EqmContextMap;
import org.xxx.socket.utils.FrameUtils;

/**
 * @author Joker
 * @ClassName:DtuController
 * @Function: DTU信息处理
 * @Date: Mar 9, 2017 9:12:26 AM
 * @see
 * @since JDK 1.8
 */
public class EqmController {

    private static final Logger logger = LoggerFactory.getLogger(EqmController.class);

    // 通道上下文属性key
    private AttributeKey<EqmContext> attreqmContext;

    // 通道上下文属性
    private EqmContext eqmContext;

    public EqmController(AttributeKey<EqmContext> attreqmContext) {
	this.attreqmContext = attreqmContext;
    }

    /**
     * heartbeat: 处理dtu的心跳报文
     *
     * @param ctx
     * @param msg
     * @author Joker
     * @since JDK 1.8
     */
    public void heartbeat(ChannelHandlerContext ctx, byte[] msg) {
	String deviceNo = FrameUtils.getDeviceNo(msg);
	if (StringUtils.isEmpty(deviceNo)) {
	    return;
	}
	updateDeviceStatus(deviceNo, ctx);
    }

    /**
     * readDevice: 处理上传的数据报文
     *
     * @param ctx
     * @param msg
     * @author Joker
     * @since JDK 1.8
     */
    public void readDevice(ChannelHandlerContext ctx, byte[] msg) {
	String deviceNo = FrameUtils.getDeviceNo(msg);
	// 更新设备状态
	updateDeviceStatus(deviceNo, ctx);
	EqmContext eqmContext = ctx.channel().attr(attreqmContext).get();
	if (eqmContext == null) {
	    return;
	}

    }

    /**
     * saveRegisterInfo: 处理采集器（dtu）注册信息
     *
     * @param ctx
     * @param msg
     * @author Joker
     * @since JDK 1.8
     */
    public void saveRegisterInfo(ChannelHandlerContext ctx, byte[] msg) {
	// 从数据帧获取设备No
	String deviceNo = FrameUtils.getDeviceNo(msg);
	if (StringUtils.isEmpty(deviceNo)) {
	    return;
	}
	eqmContext = new EqmContext();
	eqmContext.setDeviceNo(deviceNo);
	eqmContext.setDeviceCHC(ctx);

	// TODO 开启定时器

	// 封装管道上下文属性
	ctx.channel().attr(attreqmContext).set(eqmContext);
	logger.warn(ctx.channel().attr(attreqmContext).get().getDeviceNo() + " : 编号设备注册成功!");
	// 将采集器信息 保存到缓存中
	EqmContextMap.getInstance().put(deviceNo, eqmContext);
	// 更新状态
	updateDeviceStatus(deviceNo, ctx);

    }

    /**
     * updateDeviceStatus: 更新设备在线状态
     *
     * @param ctx
     * @author Joker
     * @since JDK 1.8
     */
    private void updateDeviceStatus(String collectorNo, ChannelHandlerContext ctx) {
	// TODO 更新设备状态
    }

}
